package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.enums.StatusEnum;
import com.xmy.cultivate.enums.StatusOrderApplyEnum;
import com.xmy.cultivate.enums.StatusStudentGradeEnum;
import com.xmy.cultivate.feign.english.IFeiEnglishFeignClient;
import com.xmy.cultivate.respons.ResStudentClassType;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.CommonUtil;
import com.xmy.cultivate.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 每个学期开学前需要处理的事务
 */
@RestController
@RequestMapping("/api/openSchool")
@Scope("prototype")
@Slf4j
public class OpenSchoolController extends BaseController{

    /**
     * 流程：
     * 1、先添加季度
     * 2、先备份数据库
     * 3、结班与学员结课
     * 4、添加订单数据到历史表 order_detail_history
     * 5、课程顺延前剩余课次记录添加 student_residue_course【待定确认，因为定时为自动添加一次】
     * 6、课程顺延前请假未补的，扣除金额
     * 7、课程顺延
     * 8、预分班,课程顺延后，补上订单id
     * 9、智能课，刷题班生成
     * 10、定时扣课时关闭了，记得开启
     * 11、添加当前学期校区到SchoolQuarter表
     * 12、英语学习系统，添加当前学期校区到SchoolQuarter表
     * 13、英语学习系统场地与电脑设置为对应学期
     */



    /**
     * 结班与结课
     * update grade set `status` = 2 where `status` =1 and year_part = 2024 and quarter_num =4;
     * update student_grade set `reading_status` = 5 where `reading_status` =1 and year_part = 2024 and quarter_num =4;
     *更新上个学期智能课与刷题班剩余课时为0
     * update order_detail set residue_course_count = 0,residue_price =0 where year_part = 2024 and quarter_num =4 and lesson_type in(2,3);

     * 课程顺延前检查是否有剩余课时为0金额大于0的数据
     * select * from order_detail where residue_course_count = 0 and residue_price>0 and year_part =2024 and quarter_num =4 and lesson_type = 1 and `status`<>2 ORDER BY id desc;
     *查看是否有负数
     * select id,use_price,solid_price,residue_price from order_detail where residue_course_count = 0 and residue_price<0 and year_part =2024 and quarter_num =4 and lesson_type = 1 and `status`<>2 ORDER BY id desc;
     *
     *
     * 添加数据到历史数据表
     * INSERT order_detail_history select * from order_detail where year_part = 2024 and quarter_num = 4 and id not in(select id from order_detail_history where year_part = 2024 and quarter_num = 4);
     * 删除重复的预分班
     * DELETE from student_grade where id in (select id from (select *,count(id) count from student_grade where year_part = 2024 and quarter_num =4 and lesson_type =1 and reading_status = 0 and deleted =0 GROUP BY school_id,student_id,subjects_id) as t where count>1);
     *课程顺延完检查是否顺延完所有的学生
     * select * from order_detail where residue_course_count>0 and year_part =2024 and quarter_num =4 and lesson_type =1 and deleted = 0 and `status`<>2;
     *是否暑假班，暑假班课程顺延后，学生信息要增加一个年级
     * update student set year_class_id = year_class_id + 1;
     * 课程顺延后查看剩余课时和金额是否前后一致
     * select SUM(residue_course_count) as residue_course_count,SUM(residue_price) as residue_price from order_detail where year_part = 2024 and quarter_num =4 and lesson_type =1 and `status`<>2 and deleted =0;
     * select SUM(residue_course_count) as residue_course_count,SUM(residue_price) as residue_price from order_detail_history where year_part = 2024 and quarter_num =4 and lesson_type =1 and `status`<>2 and deleted =0;
     *
     * 添加当前学期校区到SchoolQuarter表,添加方法addSchoolQuarter
     */

    /**
     * 曾令腾 课程顺延后，调整为高二年级
     */

    @Autowired
    IOpenSchoolService iOpenSchoolService;

    @Autowired
    IOrderDetailService iOrderDetailService;

    @Autowired
    ICompanyService iCompanyService;

    @Autowired
    IRecordCourseService iRecordCourseServicel;

    @Autowired
    IRecordCourseLackService iRecordCourseLackService;

    @Autowired
    IRecordCostService iRecordCostService;

    @Autowired
    IStudentGradeService iStudentGradeService;

    @Autowired
    IGradeService iGradeService;

    @Autowired
    IStudentAccountService iStudentAccountService;

    @Autowired
    IOrganizationService iOrganizationService;

    @Autowired
    IAliyunFaceService iAliyunFaceService;

    @Autowired
            @Lazy
    IStudentService iStudentService;

    @Autowired
            @Lazy
    IRadeExcludeStudentService iRadeExcludeStudentService;

    @Autowired
    IQuarterService iQuarterService;

    @Autowired
    ISchoolQuarterService iSchoolQuarterService;

    @Autowired
    IEnrollInfoService iEnrollInfoService;

    @Autowired
    IMqPushService iMqPushService;


    /**
     * 课程顺延
     * @param yearAndQuarter
     * @param plusClassNum 是否增加一个年级
     * @param nextQuarterNum
     * @return
     */
    @GetMapping("courseAuto")
    public Result courseAuto(@RequestParam(value = "yearAndQuarter") Integer yearAndQuarter,
                             @RequestParam(value = "plusClassNum") Integer plusClassNum,
                             @RequestParam(value = "nextQuarterNum") Integer nextQuarterNum,
                             @RequestParam(value = "studentId",required = false) Long studentId
                             ) {
        //Integer yearAndQuarter = 20233;//被顺延的年份与学期
        //Integer plusClassNum = 0;//年级是否要增加，1为增加一个年级
        //Integer nextQuarterNum = 4;
        Company company = iCompanyService.getOneForId(1L);
        if (company ==null || !company.getIsOpenSchool().equals(1)){
            return new Result(Code.ERROR,"","公司设置里is_open_school没有打开");
        }
        //顺延时打开
        iOpenSchoolService.courseAuto(yearAndQuarter,plusClassNum,nextQuarterNum,studentId);
        return new Result(Code.OK,"","成功");
    }


    /**
     * 智能课，刷题班生成
     * @param schoolId
     * @param yearPart
     * @param quarterNum
     * @param subjectsId
     * @param studentId
     * @return
     */
    @GetMapping("/addOtherCourse")
    public Result addOtherCourse(@RequestParam(value = "schoolId") Long schoolId,
                                 @RequestParam(value = "yearPart") Integer yearPart,
                                 @RequestParam(value = "quarterNum") Integer quarterNum,
                                 @RequestParam(value = "subjectsId") Long subjectsId,
                                 @RequestParam(value = "studentId") Long studentId) {
        Company company = iCompanyService.getOneForId(1L);
        if (company ==null || !company.getIsOpenSchool().equals(1)){
            return new Result(Code.ERROR,"","公司设置里is_open_school没有打开");
        }
        //Integer yearPart = 2023;
        //Integer quarterNum = 4;
        //Long schoolId = 1600459616684908546L;
        //Long subjectsId = 1L;
        Integer lessonType = 1;//精品课类型
        //Long studentId = 1710299844695818240L;
        iOrderDetailService.addOrderApply(yearPart, quarterNum, schoolId, subjectsId, lessonType, studentId);
        return new Result(Code.OK,"","成功");
    }

    /**
     * 预分班,课程顺延后，补上订单id
     * @param yearPart
     * @param quarterNum
     * @return
     */
    @GetMapping("/sttudentGradeAddOrderId")
    public Result studentGradeAddOrderId(@RequestParam(value = "yearPart") Integer yearPart,
                                        @RequestParam(value = "quarterNum") Integer quarterNum,
                                         @RequestParam(value = "lessonType",defaultValue = "1") Integer lessonType) {
        Company company = iCompanyService.getOneForId(1L);
        if (company ==null || !company.getIsOpenSchool().equals(1)){
            return new Result(Code.ERROR,"","公司设置里is_open_school没有打开");
        }
        iOpenSchoolService.studentGradeAddOrderId(yearPart,quarterNum,lessonType);
        return new Result(Code.OK,"","成功");
    }


    /**
     * 批量转校
     */
    @PostMapping("/batchChangeSchool")
    public Result batchChangeSchool(@RequestParam(value = "outSchoolId") Long outSchoolId,
                                    @RequestParam(value = "inSchoolId") Long inSchoolId,
                                    @RequestParam(value = "subjectsIdStr",required = false) String subjectsIdStr,
                                    @RequestParam(value = "yearClassIdStr",required = false) String yearClassIdStr) throws ParseException {
        //Long outSchoolId = 1600459509902123009L;//转出校区
        //Long inSchoolId = 1677155560973004802L;//转入校区
        Company company = iCompanyService.getOneForId(1L);
        if (company ==null || !company.getIsOpenSchool().equals(1)){
            return new Result(Code.ERROR,"","公司设置里is_open_school没有打开");
        }
        iOpenSchoolService.batchChangeSchool(outSchoolId,inSchoolId,subjectsIdStr,yearClassIdStr,this.adminId);
        return new Result(Code.OK,"","成功");
    }

    /**
     * 更新智能课，刷题班剩余课时为0
     */
    @GetMapping("/deleteOtherCourse")
    public Result deleteOtherCourse(@RequestParam(value = "yearPart") Integer yearPart,
                                         @RequestParam(value = "quarterNum") Integer quarterNum) {

        Company company = iCompanyService.getOneForId(1L);
        if (company ==null || !company.getIsOpenSchool().equals(1)){
            return new Result(Code.ERROR,"","公司设置里is_open_school没有打开");
        }
        QueryWrapper<OrderDetail> queryWrapper =  new QueryWrapper<>();
        //queryWrapper.eq("school_id",1600459698721300481L);
        queryWrapper.eq("year_part",yearPart);
        queryWrapper.eq("quarter_num",quarterNum);
        queryWrapper.gt("residue_course_count",0);
        queryWrapper.ne("lesson_type",1);//不等于精品课
        //queryWrapper.groupBy("school_id","student_id","subjects_id");
        queryWrapper.orderByAsc("school_id");
        //查找出智能课或者刷题班剩余课次大于零的数据
        List<OrderDetail> orderDetailList = iOrderDetailService.list(queryWrapper);
        Integer i =0;
        for (OrderDetail orderDetail:orderDetailList){
            //获取出精品课剩余课次
            Integer residueCourseCount = iOrderDetailService.getResidueCourseCount(orderDetail.getSchoolId(),orderDetail.getStudentId(),orderDetail.getSubjectsId(),orderDetail.getYearAndQuarter(),1);
            residueCourseCount = residueCourseCount * 3 * 2;
            if (residueCourseCount.equals(0)){
                orderDetail.setResidueCourseCount(0);
                iOrderDetailService.updateById(orderDetail);
            }else {
                orderDetail.setResidueCourseCount(residueCourseCount);
                iOrderDetailService.updateById(orderDetail);
            }
            System.out.println(orderDetailList.size()+"---i:"+i++);
        }

        /*for (OrderDetail orderDetail:orderDetailList){
            orderDetail.setResidueCourseCount(0);
            iOrderDetailService.updateById(orderDetail);
            System.out.println(orderDetailList.size()+"---i:"+i++);
        }*/
        return new Result(Code.OK,"","成功");
    }

    /**
     * 课程顺延前请假未补的，扣除金额
     * @param yearPart
     * @param quarterNum
     * @return
     */
    @GetMapping("/leaveBackMoney")
    @Transactional
    public Result leaveBackMoney(@RequestParam(value = "yearPart") Integer yearPart,
                                 @RequestParam(value = "quarterNum") Integer quarterNum){

        Company company = iCompanyService.getOneForId(1L);
        if (company ==null || !company.getIsOpenSchool().equals(1)){
            return new Result(Code.ERROR,"","公司设置里is_open_school没有打开");
        }

        QueryWrapper<RecordCourse> recordCourseQueryWrapper = new QueryWrapper<>();
        recordCourseQueryWrapper.eq("year_part",yearPart);
        recordCourseQueryWrapper.eq("quarter",quarterNum);
        recordCourseQueryWrapper.eq("status",2);
        recordCourseQueryWrapper.eq("lesson_type",1);
        recordCourseQueryWrapper.ne("is_repair",1);
        recordCourseQueryWrapper.eq("is_deduct_house",1);
        recordCourseQueryWrapper.eq("is_deduct_money",0);
        List<RecordCourse> recordCourseList = iRecordCourseServicel.list(recordCourseQueryWrapper);
        for (RecordCourse recordCourse :recordCourseList){
            RecordCourseLack recordCourseLack = iRecordCourseLackService.getById(recordCourse.getId());
            if (recordCourseLack != null){
                OrderDetail orderDetail = iOrderDetailService.getById(recordCourseLack.getOrderDetailId());
                if (orderDetail != null){
                    BigDecimal buckleClassMoney;
                    BigDecimal diffMoney = orderDetail.getResiduePrice().subtract(recordCourseLack.getBuckleClassMoney());
                    if (diffMoney.compareTo(BigDecimal.ZERO) >= 0){
                        buckleClassMoney = recordCourseLack.getBuckleClassMoney();
                    }else {
                        buckleClassMoney = orderDetail.getResiduePrice();
                    }
                    recordCourse.setBuckleClassMoney(buckleClassMoney);
                    recordCourse.setIsDeductMoney(1);
                    recordCourse.setTeacherGetMoney(recordCourseLack.getTeacherGetMoney());
                    recordCourse.setTeacherGetHouse(recordCourseLack.getTeacherGetHouse());
                    recordCourse.setRemark("课程顺延前请假未补的，扣除金额");
                    iRecordCourseServicel.updateById(recordCourse);

                    orderDetail.setResiduePrice(orderDetail.getResiduePrice().subtract(buckleClassMoney));
                    orderDetail.setUsePrice(orderDetail.getUsePrice().add(buckleClassMoney));
                    iOrderDetailService.updateById(orderDetail);

                    recordCourseLack.setIsDeductMoney(1);
                    iRecordCourseLackService.updateById(recordCourseLack);

                    RecordCost recordCost = iRecordCostService.getOneByRecordId(recordCourse.getId());
                    if (recordCost != null){
                        recordCost.setBuckleClassMoney(recordCourse.getBuckleClassMoney());
                        recordCost.setTeacherGetMoney(recordCourse.getBuckleClassMoney());
                        recordCost.setTeacherGetHouse(recordCourse.getBuckleClassHouse());
                        iRecordCostService.updateById(recordCost);
                    }

                }
            }
        }
        return new Result(Code.OK,"","成功");
    }

    /**
     * 新学期，更新学生班型
     * @param yearPart
     * @param quarterNum
     * @return
     */
    @GetMapping("/newQuarterUpdateClassType")
    public Result newQuarterUpdateClassType(@RequestParam(value = "yearPart") Integer yearPart,
                                            @RequestParam(value = "quarterNum") Integer quarterNum,
                                            @RequestParam(value = "readingStatus") Integer readingStatus,
                                            @RequestParam(value = "subjectsId",defaultValue = "1") Integer subjectsId) {
        Company company = iCompanyService.getOneForId(1L);
        if (company ==null || !company.getIsOpenSchool().equals(1)){
            return new Result(Code.ERROR,"","公司设置里is_open_school没有打开");
        }
        iStudentGradeService.newQuarterUpdateClassType(yearPart,quarterNum,readingStatus,subjectsId);
        return new Result(Code.OK,"","更新中……");
    }

    /**
     * 添加新生还没有帐号的学期
     * @param yearPart
     * @param quarterNum
     * @param readingStatus
     * @return
     */
    @GetMapping("/newStudentAddAccount")
    public Result newStudentAddAccount(@RequestParam(value = "yearPart") Integer yearPart,
                                       @RequestParam(value = "quarterNum") Integer quarterNum,
                                       @RequestParam(value = "subjectsId",defaultValue = "1") Integer subjectsId,
                                       @RequestParam(value = "studentId",required = false) String studentId,
                                       @RequestParam(value = "readingStatus",defaultValue = "1") Integer readingStatus){

        Company company = iCompanyService.getOneForId(1L);
        if (company ==null || !company.getIsOpenSchool().equals(1)){
            return new Result(Code.ERROR,"","公司设置里is_open_school没有打开");
        }

        QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
        studentGradeQueryWrapper.eq("year_part",yearPart);
        studentGradeQueryWrapper.eq("quarter_num",quarterNum);
        studentGradeQueryWrapper.eq("subjects_id",subjectsId);
        studentGradeQueryWrapper.eq(StringUtils.isNotBlank(studentId),"student_id",studentId);
        studentGradeQueryWrapper.eq("reading_status",readingStatus);
        List<Long> studentIdList = new ArrayList<>();
        studentGradeQueryWrapper.notInSql("student_id","select student_id from student_account ");
        //studentGradeQueryWrapper.in("student_id",studentIdList);
        List<StudentGrade> studentGradeList = iStudentGradeService.list(studentGradeQueryWrapper);
        Integer i = 0;
        for(StudentGrade studentGrade : studentGradeList){
            try{
                iStudentAccountService.applyAddStudentAccount(studentGrade.getSchoolId(),studentGrade.getStudentId(),studentGrade.getGradeId(),studentGrade.getCourseId());
            }catch (Exception e){
            }
            i++;
            //log.info("studentCount:"+ studentGradeList.size() +"i:"+i);
        }
        return new Result(Code.OK,"","更新中……");
    }


    /*
    设置转校后的分班状态，暂时不使用
    @GetMapping("/transferOrderDetailSetStatus")
    public Result transferOrderDetailSetStatus(@RequestParam(value = "yearPart") Integer yearPart,
                                               @RequestParam(value = "quarterNum") Integer quarterNum,
                                               @RequestParam(value = "schoolId",required = false) String schoolId){
        List<OrderDetail> orderDetailList = iOrderDetailService.getTransferOrderDetail(yearPart,quarterNum,schoolId,1);
        Integer i =0;
        for (OrderDetail orderDetail:orderDetailList){
            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
            studentGradeQueryWrapper.eq("year_part",yearPart);
            studentGradeQueryWrapper.eq("quarter_num",quarterNum);
            studentGradeQueryWrapper.eq("is_last",1);
            studentGradeQueryWrapper.eq("school_id",orderDetail.getSchoolId());
            studentGradeQueryWrapper.eq("student_id",orderDetail.getStudentId());
            studentGradeQueryWrapper.eq("subjects_id",orderDetail.getSubjectsId());
            studentGradeQueryWrapper.eq("lesson_type",orderDetail.getLessonType());
            List<StudentGrade> studentGradeList = iStudentGradeService.list(studentGradeQueryWrapper);
            for (StudentGrade studentGrade:studentGradeList){
                if (!studentGrade.getStatus().equals(StatusStudentGradeEnum.TURN)){
                    studentGrade.setStatus(StatusStudentGradeEnum.TURN);
                    iStudentGradeService.updateById(studentGrade);
                }
                i++;
            }
        }
        return new Result(Code.OK,"","成功调整了:"+i+ "条数据");
    }*/

    /**
     * 更新学生分班信息到其它系统
     * @param yearPart
     * @param quarterNum
     * @param schoolId
     * @param subjectsId
     * @return
     */
    @GetMapping("/studentClassGradePushMq")
    public Result studentClassGradePushMq(@RequestParam("yearPart") Integer yearPart,
                                          @RequestParam("quarterNum") Integer quarterNum,
                                          @RequestParam(value = "schoolId",required = false) Long schoolId,
                                          @RequestParam("subjectsId") Long subjectsId,
                                          @RequestParam(value = "studentId",required = false) Long studentId
    ){
        iStudentGradeService.studentClassGradePushMq(yearPart,quarterNum,schoolId,subjectsId,studentId);
        return new Result(Code.OK,"","");
    }

    /**
     * 添加人脸库
     * @return
     * @throws Exception
     */
    @GetMapping("/addFaceDbBatch")
    public Result addFaceDbBatch() throws Exception {
        QueryWrapper<Organization> organizationQueryWrapper = new QueryWrapper<>();
        organizationQueryWrapper.eq("type", 1);
        organizationQueryWrapper.eq("status", 1);
        organizationQueryWrapper.isNotNull("ali_account");
        organizationQueryWrapper.groupBy("ali_account");
        List<Organization> organizationList = iOrganizationService.list(organizationQueryWrapper);
        for (Organization organization : organizationList) {
            boolean rs = iAliyunFaceService.addFaceDb(organization.getId(), "default_teahcer");
            if (rs) {
                organization.setSort(1);
                iOrganizationService.updateById(organization);
            } else {
                System.out.println("添加失败id：" + organization.getId());
            }
        }
        return new Result(Code.OK,"","");
    }

    /**
     * 重置学生年级
     * @return
     */
    @GetMapping("resetYearClassId")
    public Result resetYearClassId(){
        iStudentService.resetYearClassId();
        return new Result(Code.OK,"","提交成功");
    }

    /**
     * 添加新老生排除数据
     * @return
     */
    @PostMapping("/addRadeExcludeOldData")
    public Result addRadeExcludeOldData(){
        iRadeExcludeStudentService.addOldData();
        return new Result(Code.OK,"","提交成功");
    }

    //添加当前学期校区到SchoolQuarter表
    @PostMapping("/addSchoolQuarter")
    public Result addSchoolQuarter(){
        Quarter quarterNow = iQuarterService.getNowQuarter();
        QueryWrapper<Organization> organizationQueryWrapper = new QueryWrapper<>();
        organizationQueryWrapper.eq("type",1);
        organizationQueryWrapper.eq("status",1);
        List<Organization> organizationList = iOrganizationService.list(organizationQueryWrapper);
        for (Organization organization : organizationList) {
            QueryWrapper<SchoolQuarter> schoolQuarterQueryWrapper = new QueryWrapper<>();
            schoolQuarterQueryWrapper.eq("year_part",quarterNow.getYearPart());
            schoolQuarterQueryWrapper.eq("quarter_num",quarterNow.getNum());
            schoolQuarterQueryWrapper.eq("school_id",organization.getId());
            Long count = iSchoolQuarterService.count(schoolQuarterQueryWrapper);
            if (count.equals(0L)) {
                SchoolQuarter schoolQuarter = new SchoolQuarter();
                schoolQuarter.setYearPart(quarterNow.getYearPart());
                schoolQuarter.setQuarterNum(quarterNow.getNum());
                schoolQuarter.setSchoolId(organization.getId());
                schoolQuarter.setSchoolName(organization.getName());
                schoolQuarter.setPid(organization.getPid());
                iSchoolQuarterService.save(schoolQuarter);
            }
        }
        return new Result(Code.OK,"","提交成功");
    }

    /**
     * 添加新生分层班型
     * @param yearPart
     * @param quarterNum
     * @return
     */
    @GetMapping("/addEnrollStudentTranscript")
    public Result addEnrollStudentTranscript(@RequestParam("yearPart") Integer yearPart,
                                             @RequestParam("quarterNum") Integer quarterNum,
                                             @RequestParam(value = "studentId",required = false) Long studentId
                                             ){
        iEnrollInfoService.addEnrollStudentTranscript(yearPart,quarterNum,studentId);
        return new Result(Code.OK,"","提交成功");
    }

    /**
     * 重新排课
     * @return
     */
    @GetMapping("/redoAutoScheduling")
    public Result redoAutoScheduling(@RequestParam("yearPart")Integer yearPart,
                                     @RequestParam("quarterNum")Integer quarterNum,
                                     @RequestParam(value = "schoolId",required = false)Long schoolId,
                                     @RequestParam(value = "subjectsId",required = false)Long subjectsId,
                                     @RequestParam(value = "lessonType",defaultValue = "1")Integer lessonType,
                                     @RequestParam(value = "yearClassId",required = false)String yearClassId
                                     ){
        Company company = iCompanyService.getById(1);
        if (company ==null || !company.getIsOpenSchool().equals(1)){
            return new Result(Code.ERROR,"","公司设置里is_open_school没有打开");
        }
        Quarter quarter = iQuarterService.getNowQuarter();
        if (yearPart == null){
            yearPart = quarter.getYearPart();
        }
        if (quarterNum == null){
            quarterNum = quarter.getNum();
        }

        QueryWrapper<Grade> gradeQueryWrapper = new QueryWrapper<>();
        gradeQueryWrapper.eq("year_part", yearPart);
        gradeQueryWrapper.eq("quarter_num", quarterNum);
        gradeQueryWrapper.eq(schoolId != null,"school_id", schoolId);
        gradeQueryWrapper.eq(subjectsId != null,"subjects_id", subjectsId);
        gradeQueryWrapper.eq("lesson_type", lessonType);
        gradeQueryWrapper.inSql(StringUtils.isNotBlank(yearClassId),"year_class_id", yearClassId);
        List<Grade> gradeList = iGradeService.list(gradeQueryWrapper);
        for (Grade grade : gradeList) {
            if (grade.getIsMakeup().equals(0) && grade.getIsAutoScheduling().equals(1)) {
                //schedulintCount = iCourseSchedulingService.autoScheduling(grade.getId(), null);
                iMqPushService.autoScheduling(grade.getId(),null);
            }
        }
        return new Result(Code.OK,"","提交成功");
    }

    /**
     * 根据精品课，智能课或刷题班，自动分班
     * @param yearPart
     * @param quarterNum
     * @return
     */
    @GetMapping("/autoAllotStudentGrade")
    public Result autoAllotStudentGrade(@RequestParam("yearPart") Integer yearPart,
                                             @RequestParam("quarterNum") Integer quarterNum,
                                             @RequestParam(value = "schoolId",required = false) Long schoolId,
                                             @RequestParam(value = "subjectsId",required = false) Long subjectsId,
                                             @RequestParam(value = "studentId",required = false) Long studentId
    ){
        Company company = iCompanyService.getById(1);
        if (company ==null || !company.getIsOpenSchool().equals(1)){
            return new Result(Code.ERROR,"","公司设置里is_open_school没有打开");
        }
        iStudentGradeService.autoAllotStudentGrade(yearPart,quarterNum,schoolId,subjectsId,studentId);
        return new Result(Code.OK,"","自动分班中……");
    }


    /**
     * 是否上第一次课，同步到英语系统
     * @return
     */
    @GetMapping("/updateIsUpFirst")
    public Result updateIsUpFirst(){
        Quarter quarterNow = iQuarterService.getNowQuarter();
        iRecordCourseServicel.updateIsUpFirst(quarterNow.getYearPart(),quarterNow.getNum());
        return new Result(Code.OK,"","同步中……");
    }
}
